package com.zhumiao.weixindev.util;

import com.thoughtworks.xstream.XStream;
import com.zhumiao.weixindev.entity.WeixinMessage;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class XmlUtil {
    /**
     * textMessage 转化成 xml
     * @param textMessage
     * @return
     */
    public static String textMessageToXml(WeixinMessage textMessage){
        XStream xStream = new XStream();
        xStream.alias("xml", WeixinMessage.class);
        return xStream.toXML(textMessage);
    }
    /**
     * 将xml转换成map集合
     * @param request
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();

        InputStream inputStream = request.getInputStream();
        Document doc = reader.read(inputStream);

        Element root = doc.getRootElement();

        List<Element> list = root.elements();

        for(Element e : list){
            map.put(e.getName(), e.getText());
        }
        inputStream.close();
        return map;
    }
}
